import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Grid,
  Card,
  CardContent,
  Typography,
  Avatar,
  Paper,
  Button,
  LinearProgress,
  Chip,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Divider,
  Alert,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  CircularProgress,
  Stack,
  Switch,
  FormControlLabel
} from '@mui/material';
import {
  Business,
  People,
  AccountTree,
  TrendingUp,
  TrendingDown,
  Notifications,
  Security,
  Storage,
  Speed,
  CheckCircle,
  Warning,
  Error,
  Info,
  PersonAdd,
  Group,
  Settings,
  Assessment,
  Timeline,
  PieChart,
  BarChart,
  Refresh
} from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';

import { useAuth } from '@/stores';
import { settingsService } from '@/services/settingsService';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

// 统计卡片组件
interface StatCardProps {
  title: string;
  value: string | number;
  icon: React.ReactNode;
  color: string;
  trend?: {
    value: string;
    isPositive: boolean;
  };
  loading?: boolean;
}

const StatCard: React.FC<StatCardProps> = ({ title, value, icon, color, trend, loading }) => (
  <Card sx={{ height: '100%', position: 'relative' }}>
    <CardContent>
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Box sx={{ flex: 1 }}>
          {loading ? (
            <CircularProgress size={24} sx={{ mb: 1 }} />
          ) : (
            <Typography variant="h4" sx={{ fontWeight: 600, color, mb: 0.5 }}>
              {value}
            </Typography>
          )}
          <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
            {title}
          </Typography>
          {trend && (
            <Typography 
              variant="caption" 
              color={trend.isPositive ? 'success.main' : 'error.main'} 
              sx={{ display: 'flex', alignItems: 'center' }}
            >
              {trend.isPositive ? <TrendingUp fontSize="small" sx={{ mr: 0.5 }} /> : <TrendingDown fontSize="small" sx={{ mr: 0.5 }} />}
              {trend.value}
            </Typography>
          )}
        </Box>
        <Avatar sx={{ bgcolor: color, width: 56, height: 56 }}>
          {icon}
        </Avatar>
      </Box>
    </CardContent>
  </Card>
);

// 进度指标组件
interface ProgressMetricProps {
  title: string;
  current: number;
  total: number;
  color?: 'primary' | 'secondary' | 'success' | 'warning' | 'error';
  format?: (value: number) => string;
}

const ProgressMetric: React.FC<ProgressMetricProps> = ({ 
  title, 
  current, 
  total, 
  color = 'primary',
  format = (value) => value.toString()
}) => {
  const percentage = Math.min((current / total) * 100, 100);
  
  return (
    <Box sx={{ mb: 2 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
        <Typography variant="body2" color="text.secondary">
          {title}
        </Typography>
        <Typography variant="body2" sx={{ fontWeight: 'medium' }}>
          {format(current)} / {format(total)}
        </Typography>
      </Box>
      <LinearProgress 
        variant="determinate" 
        value={percentage} 
        color={color}
        sx={{ height: 8, borderRadius: 4 }}
      />
      <Typography variant="caption" color="text.secondary" sx={{ mt: 0.5, display: 'block' }}>
        {percentage.toFixed(1)}% 已使用
      </Typography>
    </Box>
  );
};

export const DashboardPage: React.FC = () => {
  const navigate = useNavigate();
  const { user, currentTenant } = useAuth();
  const [autoRefresh, setAutoRefresh] = useState(false);

  // 获取系统统计数据
  const { data: systemStats, isLoading: statsLoading } = useQuery({
    queryKey: ['system-stats'],
    queryFn: () => settingsService.getSystemStats(),
    refetchInterval: autoRefresh ? 30000 : false // 自动刷新
  });

  // 模拟实时数据
  const realtimeStats = useMemo(() => {
    if (!systemStats) {
      return {
        totalUsers: 0,
        activeUsers: 0,
        totalTenants: 0,
        activeTenants: 0,
        totalOrganizations: 0,
        storageUsed: 0,
        storageTotal: 10240,
        auditLogCount: 0
      };
    }
    return systemStats;
  }, [systemStats]);

  // 统计卡片数据
  const stats = [
    {
      title: '租户总数',
      value: realtimeStats.totalTenants,
      icon: <Business />,
      color: '#1976d2',
      trend: { value: '+12%', isPositive: true },
      loading: statsLoading
    },
    {
      title: '活跃用户',
      value: realtimeStats.activeUsers.toLocaleString(),
      icon: <People />,
      color: '#2e7d32',
      trend: { value: '+8%', isPositive: true },
      loading: statsLoading
    },
    {
      title: '组织机构',
      value: realtimeStats.totalOrganizations,
      icon: <AccountTree />,
      color: '#ed6c02',
      trend: { value: '+15%', isPositive: true },
      loading: statsLoading
    },
    {
      title: '审计日志',
      value: realtimeStats.auditLogCount.toLocaleString(),
      icon: <Security />,
      color: '#9c27b0',
      trend: { value: '+156', isPositive: true },
      loading: statsLoading
    },
  ];

  // 模拟近期活动
  const recentActivities = [
    {
      id: 1,
      title: '新用户注册',
      description: '张三加入了阿里云科技',
      time: '2分钟前',
      type: 'user',
      icon: <PersonAdd />,
      color: 'primary'
    },
    {
      id: 2,
      title: '租户创建',
      description: '创建了新租户"腾讯云计算"',
      time: '15分钟前',
      type: 'tenant',
      icon: <Business />,
      color: 'success'
    },
    {
      id: 3,
      title: '权限变更',
      description: '更新了角色"组织管理员"的权限',
      time: '1小时前',
      type: 'permission',
      icon: <Security />,
      color: 'warning'
    },
    {
      id: 4,
      title: '系统公告',
      description: '系统将于今晚24:00进行维护',
      time: '2小时前',
      type: 'notice',
      icon: <Notifications />,
      color: 'info'
    },
  ];

  // 系统健康状态
  const systemHealth = [
    { name: 'API服务', status: 'healthy', uptime: '99.9%', responseTime: '45ms' },
    { name: '数据库', status: 'healthy', uptime: '99.8%', responseTime: '12ms' },
    { name: '缓存服务', status: 'warning', uptime: '98.5%', responseTime: '8ms' },
    { name: '文件存储', status: 'healthy', uptime: '99.9%', responseTime: '23ms' },
  ];

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'healthy': return 'success';
      case 'warning': return 'warning';
      case 'error': return 'error';
      default: return 'default';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'healthy': return <CheckCircle />;
      case 'warning': return <Warning />;
      case 'error': return <Error />;
      default: return <Info />;
    }
  };

  // 快捷操作
  const quickActions = [
    {
      title: '用户管理',
      description: '管理系统用户',
      icon: <People />,
      color: '#1976d2',
      path: '/users'
    },
    {
      title: '租户管理',
      description: '管理租户信息',
      icon: <Business />,
      color: '#2e7d32',
      path: '/tenants'
    },
    {
      title: '角色权限',
      description: '配置角色权限',
      icon: <Security />,
      color: '#ed6c02',
      path: '/roles'
    },
    {
      title: '系统设置',
      description: '系统配置管理',
      icon: <Settings />,
      color: '#9c27b0',
      path: '/settings/tenant'
    },
  ];

  return (
    <Box sx={{ p: 3 }}>
      {/* 页面标题和控制 */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
        <Box>
          <Typography variant="h4" sx={{ fontWeight: 600, mb: 1 }}>
            欢迎回来，{user?.profile.fullName}！
          </Typography>
          <Typography variant="body1" color="text.secondary">
            {format(new Date(), 'yyyy年MM月dd日 EEEE', { locale: zhCN })}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <FormControlLabel
            control={
              <Switch
                checked={autoRefresh}
                onChange={(e) => setAutoRefresh(e.target.checked)}
                size="small"
              />
            }
            label="自动刷新"
          />
          <Button
            variant="outlined"
            startIcon={<Refresh />}
            onClick={() => window.location.reload()}
          >
            刷新数据
          </Button>
        </Box>
      </Box>

      {/* 统计卡片 */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        {stats.map((stat, index) => (
          <Grid item xs={12} sm={6} md={3} key={index}>
            <StatCard {...stat} />
          </Grid>
        ))}
      </Grid>

      {/* 主要内容区域 */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        {/* 系统健康状态 */}
        <Grid item xs={12} lg={8}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 3 }}>
                <Typography variant="h6" sx={{ fontWeight: 600 }}>
                  系统健康状态
                </Typography>
                <Chip label="实时监控" color="success" size="small" />
              </Box>
              
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow>
                      <TableCell>服务</TableCell>
                      <TableCell>状态</TableCell>
                      <TableCell>运行时间</TableCell>
                      <TableCell>响应时间</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {systemHealth.map((service) => (
                      <TableRow key={service.name}>
                        <TableCell>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            {getStatusIcon(service.status)}
                            {service.name}
                          </Box>
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={service.status === 'healthy' ? '正常' : service.status === 'warning' ? '警告' : '错误'}
                            color={getStatusColor(service.status) as any}
                            size="small"
                            variant="outlined"
                          />
                        </TableCell>
                        <TableCell>{service.uptime}</TableCell>
                        <TableCell>{service.responseTime}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            </CardContent>
          </Card>
        </Grid>

        {/* 资源使用情况 */}
        <Grid item xs={12} lg={4}>
          <Card sx={{ height: '100%' }}>
            <CardContent>
              <Typography variant="h6" sx={{ fontWeight: 600, mb: 3 }}>
                资源使用情况
              </Typography>
              
              <ProgressMetric
                title="存储空间"
                current={realtimeStats.storageUsed}
                total={realtimeStats.storageTotal}
                color="primary"
                format={(value) => `${value} MB`}
              />
              
              <ProgressMetric
                title="活跃用户"
                current={realtimeStats.activeUsers}
                total={realtimeStats.totalUsers}
                color="success"
              />
              
              <ProgressMetric
                title="活跃租户"
                current={realtimeStats.activeTenants}
                total={realtimeStats.totalTenants}
                color="warning"
              />
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <Grid container spacing={3}>
        {/* 快捷操作 */}
        <Grid item xs={12} md={8}>
          <Card>
            <CardContent>
              <Typography variant="h6" sx={{ fontWeight: 600, mb: 3 }}>
                快捷操作
              </Typography>
              
              <Grid container spacing={2}>
                {quickActions.map((action, index) => (
                  <Grid item xs={12} sm={6} key={index}>
                    <Paper
                      sx={{
                        p: 2,
                        cursor: 'pointer',
                        transition: 'all 0.2s',
                        '&:hover': {
                          boxShadow: 4,
                          transform: 'translateY(-2px)'
                        }
                      }}
                      onClick={() => navigate(action.path)}
                    >
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                        <Avatar sx={{ bgcolor: action.color, width: 40, height: 40 }}>
                          {action.icon}
                        </Avatar>
                        <Box>
                          <Typography variant="subtitle1" sx={{ fontWeight: 'medium' }}>
                            {action.title}
                          </Typography>
                          <Typography variant="body2" color="text.secondary">
                            {action.description}
                          </Typography>
                        </Box>
                      </Box>
                    </Paper>
                  </Grid>
                ))}
              </Grid>
            </CardContent>
          </Card>
        </Grid>

        {/* 近期活动 */}
        <Grid item xs={12} md={4}>
          <Card sx={{ height: '100%' }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
                <Typography variant="h6" sx={{ fontWeight: 600 }}>
                  近期活动
                </Typography>
                <Timeline color="action" />
              </Box>
              
              <List dense>
                {recentActivities.map((activity, index) => (
                  <React.Fragment key={activity.id}>
                    <ListItem sx={{ px: 0 }}>
                      <ListItemAvatar>
                        <Avatar 
                          sx={{ 
                            width: 32, 
                            height: 32, 
                            bgcolor: `${activity.color}.main` 
                          }}
                        >
                          {activity.icon}
                        </Avatar>
                      </ListItemAvatar>
                      <ListItemText
                        primary={
                          <Typography variant="body2" sx={{ fontWeight: 'medium' }}>
                            {activity.title}
                          </Typography>
                        }
                        secondary={
                          <Box>
                            <Typography variant="caption" color="text.secondary">
                              {activity.description}
                            </Typography>
                            <Typography variant="caption" color="text.secondary" display="block">
                              {activity.time}
                            </Typography>
                          </Box>
                        }
                      />
                    </ListItem>
                    {index < recentActivities.length - 1 && <Divider variant="inset" component="li" />}
                  </React.Fragment>
                ))}
              </List>
              
              <Button 
                variant="text" 
                size="small" 
                sx={{ mt: 2, textTransform: 'none' }}
                onClick={() => navigate('/settings/audit-logs')}
              >
                查看全部活动
              </Button>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );
};

export default DashboardPage;